﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Catalyst.Mvc.Extensions;
using Trirand.Web.Mvc;

namespace Catalyst.Mvc
{
	public partial class LiteGrid<TGrid>
	{
		private JQGridColumn getSearchColumn<TDataType>(string dataField)
		{
			JQGridColumn column = Columns.Find(c => c.DataField == dataField);
			column.DataType = typeof(TDataType);
			column.Searchable = true;

			return column;
		}

		public void MakeSearchTextBox<TDataType>(SearchOperation searchOperation, bool isCaseSensitive, params string[] dataFields)
		{
			foreach (string dataField in dataFields)
			{
				JQGridColumn column = getSearchColumn<TDataType>(dataField);
				column.SearchType = SearchType.TextBox;
				column.SearchToolBarOperation = searchOperation;
				column.SearchCaseSensitive = isCaseSensitive;
			}
		}

		public void MakeSearchAutoComplete<TDataType>(SearchOperation searchOperation, bool isCaseSensitive, string dataField, string searchControlID)
		{
			JQGridColumn column = getSearchColumn<TDataType>(dataField);
			column.SearchType = SearchType.AutoComplete;
			column.SearchToolBarOperation = searchOperation;
			column.SearchCaseSensitive = isCaseSensitive;
			column.SearchControlID = searchControlID;
		}

		public void MakeSearchDropDownList<TDataType>(IEnumerable<SelectListItem> searchList, SearchOperation searchOperation, bool sort, params string[] dataFields)
		{
			List<SelectListItem> list = new List<SelectListItem>();

			if (sort)
			{
				list.Sort(new Comparison<SelectListItem>(delegate(SelectListItem x, SelectListItem y)
				{
					return x.Text.CompareTo(y.Text);
				}));
			}

			foreach (string dataField in dataFields)
			{
				JQGridColumn column = getSearchColumn<TDataType>(dataField);
				column.SearchType = SearchType.DropDown;
				column.SearchToolBarOperation = searchOperation;
				column.SearchList = list;
			}
		}

		public void MakeSearchBoolean(string trueText, string falseText, params string[] dataFields)
		{
			List<string> yesno = new List<string>()
			{
				trueText,
				falseText
			};

			MakeSearchDropDownList<bool>(yesno.ToSelectList(x => x, x => x), SearchOperation.IsEqualTo, false, dataFields);
		}
	}
}
